package com.meepo.sdk.component.view

import android.util.Log
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers


/**
 * @author
 *
 * @date  2020/10/14 3:32 PM
 * @version 1.0
 */
class Presenter(private val view: IView) {

    fun <T> call(
        observable: Observable<T>,
        onSuccessFunc: (t: T) -> Unit = { _ -> },
        onErrorFunc: (e: Throwable?) -> Unit = { _ -> },
        onCompleteFunc: () -> Unit = {},
        onSubscribeFunc: (d: Disposable?) -> Unit = { _ -> }
    ) {
        observable
            .subscribeOn(Schedulers.io())
            .unsubscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())

            .compose(view.bindToLife<T>())

            .subscribe(object : Observer<T> {
                override fun onComplete() {
                    onCompleteFunc()
                }

                override fun onSubscribe(d: Disposable) {
                    onSubscribeFunc(d)
                }

                override fun onNext(t: T) {
                    onSuccessFunc(t)
                }

                override fun onError(e: Throwable) {

                    //  onNext called with null. Null values are generally not allowed in 2.x operators and sources.
                    Log.e("Presenter", "" + e.message)
                    onErrorFunc(e)
                }
            })
    }


}